import axios from 'axios'
// import useEnv from '@/hooks/env';
import { Message } from '@arco-design/web-vue'
import { getToken, clearToken } from '@/utils/auth'

const service = axios.create({
  // baseURL: "https://sjlm.ltd",
  // baseURL: "http://127.0.0.1:4523/m1/1847005-0-default",
  // baseURL: env.VITE_API_BASE_URL,
  timeout: 20000
})

/* 请求拦截器 */
service.interceptors.request.use(
  (config) => {
    // config.headers!["Content-Type"] = "application/json;charset=UTF-8";
    // config.headers!["Access-Control-Allow-Origin"] = "*";
    //  伪代码
    const token = getToken()

    if (token) {
      config.headers['x-token'] = `${token}`
    }
    return config
  },
  (error) => {
    Message.error(error.message || 'error')
    return Promise.reject(error)
  }
)

/* 响应拦截器 */
service.interceptors.response.use(
  (response) => {
    const { code, data, msg: message } = response.data

    // 根据自定义错误码判断请求是否成功
    if (code === 200) {
      return data
    }
    if (code === 401) {
      setTimeout(() => {
        clearToken()
        // history.go(0);
      })
    }
    Message.error(message || 'error')
    return Promise.reject(new Error(message || 'error'))
  },
  (error) => {
    // 处理 HTTP 网络错误
    let messages = ''
    // HTTP 状态码
    const status = error.response?.status

    switch (status) {
      case 401:
        messages = 'token 失效，请重新登录'
        // 这里可以触发退出的 action
        break
      case 403:
        messages = '拒绝访问'
        break
      case 404:
        messages = '请求地址错误'
        break
      case 500:
        messages = '服务器故障'
        break
      default:
        messages = '网络连接故障'
    }

    // ElMessage.error(message);
    Message.error(messages || 'error')
    return Promise.reject(error)
  }
)

/* 导出封装的请求方法 */
export const request = {
  get(url, data, config) {
    return service.get(url, {
      ...config,
      params: data
    })
  },

  post(url, data, config) {
    return service.post(url, data, config)
  },

  put(url, data, config) {
    return service.put(url, data, config)
  },

  delete(url, data, config) {
    return service.delete(url, {
      ...config,
      params: data
    })
  }
}

/* 导出 axios 实例 */
export default request
